package com.xiaoyu.dfs;

/**
 * @program: DS_and_A
 * @description:
 * 给你一个由'1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。
 *
 * 岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
 *
 * 此外，你可以假设该网格的四条边均被水包围。
 *
 * 示例 1：
 *
 * 输入：grid = [
 *   ["1","1","1","1","0"],
 *   ["1","1","0","1","0"],
 *   ["1","1","0","0","0"],
 *   ["0","0","0","0","0"]
 * ]
 * 输出：1
 *
 * 输入：grid = [
 *   ["1","1","0","0","0"],
 *   ["1","1","0","0","0"],
 *   ["0","0","1","0","0"],
 *   ["0","0","0","1","1"]
 * ]
 * 输出：3
 *
 * @author: YuWenYi
 * @create: 2021-06-04 08:17
 **/
public class NumIslands_200 {
    //右,上,左,下
    public static final int[][] DIRECTIONS = {{0,1},{-1,0},{0,-1},{1,0}};
    public char[][] grid;   //使用全局变量,保证全局就只有一个grid

    public int numIslands(char[][] grid) {
        int row = grid.length;
        int col = grid[0].length;
        this.grid = grid;
        //走过的陆地由'1',改成'0'
        int res = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == '1'){  //一但某个岛屿是1,那么就res就一定会加1
                    dfs(i, j);
                    res++;
                }
            }
        }
        return res;
    }
    public void dfs(int row,int col){
        if (grid[row][col] == '0'){
            return;
        }
        if (grid[row][col] == '1'){   //如果岛的格子没有走过,那么就去走它
            grid[row][col] = '2';  //岛已经被走了
            for (int[] direction : DIRECTIONS) {
                int nRow = row + direction[0];
                int nCol = col + direction[1];
                if (inGrid(nRow, nCol)){  //只有在地图里,才去遍历
                    dfs(nRow, nCol);
                }
            }
        }
    }
    public boolean inGrid(int row,int col){
        return row>=0 && row < grid.length && col>=0 && col < grid[0].length;
    }


    public static void main(String[] args) {
        char[][] grid = {
                {'1','1','1','1','0'},
                {'1','1','0','1','0'},
                {'1','1','0','0','0'},
                {'0','0','0','1','0'}
        };
        NumIslands_200 numIslands_200 = new NumIslands_200();
        System.out.println(numIslands_200.numIslands(grid));

    }
}
